package momo.app.config;

import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.PropertyResourceBundle;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ResourceConfig
{	
	private final static int DEFAULT_COMM_PORT = 1791;
	private final static int DEFAULT_STATUS_PORT = 1792;
	
	public final static String COMM_PORT = "commPort";
	public final static String STATUS_PORT = "statusPort";
	
	private PropertyResourceBundle resource;
	private static ResourceConfig config;
	private final String filename = "app.ini";
	
	public static ResourceConfig getInstance() throws IOException
	{
		if ( config == null )
			config = new ResourceConfig();
		return config;
	}
	
	private ResourceConfig() throws IOException
	{
		resource = new PropertyResourceBundle(new FileReader("config/"+filename));
	}
	
	public String getProperty(String key)
	{
		return resource.getString(key);
	}
	
	public static int getCommPort()
	{
		try
		{
			return Integer.parseInt(ResourceConfig.getInstance().getProperty(ResourceConfig.COMM_PORT));
		}catch (Exception e)
		{
			Log log = LogFactory.getLog(ResourceConfig.class);
			log.error("Exception", e);
		}
		return DEFAULT_COMM_PORT;
	}
	
	public static int getStatusPort()
	{
		try
		{
			return Integer.parseInt(ResourceConfig.getInstance().getProperty(ResourceConfig.STATUS_PORT));
		}catch (Exception e)
		{
			Log log = LogFactory.getLog(ResourceConfig.class);
			log.error("Exception", e);
		}
		return DEFAULT_STATUS_PORT;
	}
	
	public static List<InetAddress> getIPAddress()
	{
		Vector<InetAddress> addresses = new Vector<InetAddress>();
		
		try
		{
			for ( Enumeration<NetworkInterface> enNI = NetworkInterface.getNetworkInterfaces(); enNI.hasMoreElements(); )
			{
				NetworkInterface ni = enNI.nextElement();
				for( Enumeration<InetAddress> enIA = ni.getInetAddresses(); enIA.hasMoreElements(); )
				{
					InetAddress add = enIA.nextElement();
					if ( !add.isLoopbackAddress() )
					{
						String address = add.getHostAddress();
						if ( address.indexOf(":") < 0 )
							addresses.add(InetAddress.getByName(address));
					}
				}
			}
		}catch(Exception e)
		{
			Log log = LogFactory.getLog(ResourceConfig.class);
			log.error("Exception", e);
		}
		
		if ( addresses.isEmpty() )
		{
			try
			{
				addresses.add(InetAddress.getByName("127.0.0.1"));
			}catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		
		return Collections.unmodifiableList(addresses);
	}
	
}//end of class Configuration
